<template>
  <span @click="getRoad">实时路况</span>
</template>
<script setup>
import { getCurrentInstance } from "vue";
const { proxy } = getCurrentInstance();

import { Query } from "@/zondyTools/mapgis-api/Query";
/* 设置不同颜色的属性信息 */
const redStyle = new ol.style.Style({
  stroke: new ol.style.Stroke({
    color: "red",
    width: 5,
  }),
});
const yellowStyle = new ol.style.Style({
  stroke: new ol.style.Stroke({
    color: "yellow",
    width: 5,
  }),
});
const greenStyle = new ol.style.Style({
  stroke: new ol.style.Stroke({
    color: "green",
    width: 5,
  }),
});

 /* 设置实时路况图层 数据源 和 图层样式 */
  const source = new ol.source.Vector({
    features: [],
  });
  const layer = new ol.layer.Vector({
    source: source,
  });

  /* 全局切换实时路况图层 */
  let isToggle = false;


const getRoad = () => {
    isToggle = !isToggle;
    const $map = proxy.$map;

    if(!isToggle){
        /* 关闭实时路况图层 */
        source.clear();
        $map.removeLayer(layer);
        return;
    };
    $map.addLayer(layer);
  let service = {
    name: "guanggu",
    layerId: 1,
  };
  Query.queryByLayerId({
    service,
    success: (res) => {
      res.forEach((item) => {
        //console.log(item.getGeometry());
        //console.log(item.getProperties().values_);
        // 绘制路况图层
        const feature = new ol.Feature({
          geometry: new ol.geom.LineString(
            toTwoArr(item.getGeometry().flatCoordinates)
          ),
          flow: item.getProperties().values_.车流量,
        });
        activeStyle({ feature, flow: item.getProperties().values_.车流量 });

        source.addFeature(feature);
      });
    },
  });
};

/* 将flatCoordinates转为二维数组 */
const toTwoArr = (arr) => {
  let result = [];
  for (let i = 0; i < arr.length; i += 2) {
    result.push([arr[i], arr[i + 1]]);
  }
  return result;
};

/* 根据不同的车流量设置不同的颜色 */
const activeStyle = ({ feature, flow }) => {
  if (flow <= 1200) {
    feature.setStyle(greenStyle);
  } else if (flow > 1200 && flow <= 1600) {
    feature.setStyle(yellowStyle);
  } else {
    feature.setStyle(redStyle);
  }
};
</script>
<style scoped></style>
